package org.example.algorithm.linkedlist;

import java.util.HashSet;

public class ListCircleSolution {
    public static void main(String[] args) {

    }
    public boolean hasCycle(ListNode head) {
        ListNode cursorSlow = head;
        ListNode cursorFast = head;
        while (cursorSlow != null && cursorFast != null) {
            cursorSlow = cursorSlow.next;
            if (cursorFast.next == null) {
                return false;
            }
            cursorFast = cursorFast.next.next;
            if (cursorFast == cursorSlow) {
                return true;
            }
        }
        return false;
    }

    public boolean hasCycle2(ListNode head) {
        HashSet nodeHashSet = new HashSet();
        ListNode cursor = head;
        while (cursor != null) {
            cursor = cursor.next;
            if (!nodeHashSet.add(cursor)) {
                return true;
            }
        }
        return false;
    }
}
